var util = require('../../../utils/util.js');
const db = wx.cloud.database();
const shopCar = db.collection("shopCar");
const myOrder = db.collection("myOrder");
const myPlaceInfo=db.collection("myPlace");
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    choosedGoods: [],
    price: 0.00,
    myPlaceId:'',
    userInfo:[],
    goodsId:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options.price)

    this.setData({
      price: (options.price / 100).toFixed(2)
    })
    //访问选中的商品购信息
    wx.cloud.callFunction({//调用云函数
      name: "checkShopCarChoosed"// 要调用的云函数名称
    }).then(res=>{
      console.log(res.result.data),
      this.setData({
        choosedGoods: res.result.data
      })
    }) 
    
   
    //获取我的个人地址信息
    wx.cloud.callFunction({
      name:'userPlaceStart'
    }).then(res=>{
      console.log(res.result.data[0])
      this.setData({
        userInfo:res.result.data[0]
      })
    })
    // myPlaceInfo.limit(1).get().then(res=>{
    //   console.log(res.data[0])
    //   this.setData({
    //     userInfo:res.data[0]
    //   })
    // }) 

    // 获取到上一页返回回来带的值
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    this.setData({
       myPlaceId:currPage.data.placeId
    })
    console.log(this.data.myPlaceId)
  },
  tapToMyPlace:function(res){
    wx.navigateTo({
      url: '../../my/myPlace/myPlace?choose='+1
    })
  },
  //确认订单
  submit: function(event) {
    var that = this;
    wx.showModal({
      title: '付款',
      content: '确认付款吗？',
      success: function(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '付款中'
          })
          setTimeout(function() {
            wx.hideLoading(),
              wx.showToast({
                title: '付款成功',
                duration: 1000,
                icon: "success",
                mask: true
              })
          }, 2000)
          wx.cloud.callFunction({
            name: 'deleteBatchCard',
            data: {
              dbName: 'shopCar' 
            }
          }).then(res => {
            console.log(res.result)
            that.setData({
              price: 0.00,
              choosedGoods: []
            })
          }).catch(console.error)
          that.addMyOrder();
        } else if (res.cancel) {
          console.log("用户点击了取消");
        }
      }
    })
  },
  orderCode:function() {
    var orderCode = '';
    for (var i = 0; i < 6; i++) //6位随机数，用以加在时间戳后面。  
    {
      orderCode += Math.floor(Math.random() * 10);
    }
    orderCode = new Date().getTime() + orderCode; //时间戳，用来生成订单号。   
    console.log(orderCode)
    
    this.setData({
      orderCode:orderCode
    })
  },

  addMyOrder() {
    const _ = db.command;
    var choosedGoods = this.data.choosedGoods;
    console.log(choosedGoods)
    for(var i=0;i<choosedGoods.length;i++){
      this.data.goodsId.push(choosedGoods[i]._id)
      console.log(choosedGoods[i]._id)
      shopCar.doc(choosedGoods[i]._id).field({
       goodsDBName:true
      }).get().then(res=>{
        console.log(res.data._id)
           //更新销量
           wx.cloud.callFunction({
             name:'saleCalculate',
             data:{
              dbName:res.data.goodsDBName,
              id:res.data._id
             }
           }).then(res=>{
             console.log(res)
           })
       })
   }

    this.orderCode();
    var orderId = this.data.orderCode;
    console.log(orderId)
    myOrder.add({
        data: {
          payerName: app.globalData.g_userInfo.nickName,
          buyerName: this.data.userInfo.userName,
          ordernumber: choosedGoods.length,
          orderTime: util.formatTime(new Date),
          orderDate:util.formatDate(new Date),
          payMoney: this.data.price,
          buyerPhone: this.data.userInfo.userNumber,
          buyerPlace: this.data.userInfo.userPlace,
          payStatus: 1,
          goodsStatus: 1,
          detail: [],
          orderId:orderId
        }
      })
      .then(res => {
        console.log(res._id)
        for (var i = 0; i < choosedGoods.length; i++) {
          myOrder.doc(res._id).update({
            data: {
              detail: _.push([
                {
                  name: choosedGoods[i].name,
                  num: choosedGoods[i].num,
                  price: choosedGoods[i].price,
                  src: choosedGoods[i].src,
                  text: choosedGoods[i].text,
                  title: choosedGoods[i].title
                }
              ])
            }
          }).then(res => {
            console.log(res)
          })
        }
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // 获取到上一页返回回来带的值
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    this.setData({
      myPlaceId: currPage.data.placeId
    })
  
    console.log(this.data.myPlaceId)
    if(!this.data.myPlaceId){
      wx.cloud.callFunction({
        name:'userPlaceStart'
      }).then(res=>{
        console.log(res.result.data[0])
        this.setData({
          userInfo:res.result.data[0]
        })
      })
    }
    else{
      myPlaceInfo.doc(this.data.myPlaceId).get().then(res => {
        console.log(res.data)
        this.setData({
          userInfo: res.data
        })
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})